package cn.tom.tompicturebackend.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.tom.tompicturebackend.config.CosClientConfig;
import cn.tom.tompicturebackend.exception.BusinessException;
import cn.tom.tompicturebackend.exception.ErrorCode;
import cn.tom.tompicturebackend.exception.ThrowUtils;
import cn.tom.tompicturebackend.model.dto.file.UploadPictureResult;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class FileManager {
    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    @Resource
    private static COSClient cosClient;

    public UploadPictureResult uploadPictureResult(MultipartFile multipartFile,String uploadPathPrefix)
    {

        //检验图片
        validPicture(multipartFile);
        //图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originFileName = multipartFile.getOriginalFilename();
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),uuid, FileUtil.getSuffix(originFileName));
        String uploadPath = String.format("/%s/%s",uploadPathPrefix,uploadFileName);
        File file = null;
        try{
            //创建临时文件
            file = File.createTempFile(uploadPath,null);
            multipartFile.transferTo(file);

            //上传图片到对象存储
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath,file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();


            if (CollUtil.isNotEmpty(objectList)){
                CIObject compressCiObject = objectList.get(0);

                //获取图片信息
                return buildResult(originFileName,compressCiObject);
            }

            //封装返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();

            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight,2).doubleValue();
            uploadPictureResult.setPicName(FileUtil.mainName(originFileName));
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setUrl(cosClientConfig.getHost()+"/"+uploadPath);
            return uploadPictureResult;

        }catch (Exception exception){
            log.error("图片上传到对象存储失败",exception);
            throw  new BusinessException(ErrorCode.SYSTEM_ERROR,"上传失败");
        }finally {
            this.deleteTempFile(file);
        }

    }

    public void validPicture(MultipartFile multipartFile){
        ThrowUtils.throwIf(multipartFile == null,ErrorCode.PARAMS_ERROR,"文件不能为空");
        //1、检验文件大小
        long fileSize = multipartFile.getSize();
        final long ONE_M = 1024 * 1024L;
        ThrowUtils.throwIf(fileSize > 2 * ONE_M,ErrorCode.PARAMS_ERROR,"文件大小不能超过2 M");

        //2、检验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());

        //允许上传的文件后缀
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpeg","jpg","png","webp");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix),ErrorCode.PARAMS_ERROR,"文件类型错误");
    }
    /**
     * 删除临时文件
     */
    public void deleteTempFile(File file){
        if(file == null){
            return;
        }
        //删除临时文件
        boolean deleteResult = file.delete();
        if(!deleteResult){
            log.error("file delete error,filepath = {}",file.getAbsoluteFile());
        }
    }

    /**
     * 扩展
     */

    public static String uploadToCOS(MultipartFile multipartFile,String bucketName, String key)throws Exception
    {
        //创建COS 客户

        try (InputStream inputStream = multipartFile.getInputStream()) {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(multipartFile.getSize());
            objectMetadata.setContentType(multipartFile.getContentType());

            //创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, objectMetadata);

            //上传
            cosClient.putObject(putObjectRequest);

            //生成访问链接
            return "https://"+bucketName+".cos."+cosClient.getClientConfig().getRegion().getRegionName()+".myqcloud.com/"+key;
        }finally {
            cosClient.shutdown();
        }

    }


    private UploadPictureResult buildResult(String originFileName, CIObject compressedCiObject)
    {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();

        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());

        //设置图片为压缩后的地址
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/"+compressedCiObject.getKey());
        return uploadPictureResult;

    }
}
